using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;

using WL.Think.Abp.EntityFrameworkCore;

namespace Volo.Abp.Modularity;

public static class PostgreSqlExtension
{
    /// <summary>
    /// 配置PG数据库时间戳行为
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ServiceConfigurationContext ConfigurePgTimestamp(this ServiceConfigurationContext context)
    {
        AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
        return context;
    }

    /// <summary>
    /// 配置PG数据库
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ServiceConfigurationContext ConfigureNpgsql(this ServiceConfigurationContext context)
    {
        context.Services.Configure<AbpDbContextOptions>(opts => opts.UseNpgsql());
        return context;
    }


    /// <summary>
    /// 配置DbContext上下文
    /// </summary>
    /// <typeparam name="TDbContext"></typeparam>
    /// <param name="context"></param>
    /// <param name="optionsBuilder"></param>
    /// <returns></returns>
    public static ServiceConfigurationContext ConfigureDbContext<TDbContext>(this ServiceConfigurationContext context, Action<IAbpDbContextRegistrationOptionsBuilder>? optionsBuilder = null) where TDbContext : AppDbContextBase<TDbContext>
    {
        context.Services.AddAbpDbContext<TDbContext>(opts =>
        {
            opts.AddDefaultRepositories(true);
            optionsBuilder?.Invoke(opts);
        });

        return context;
    }
}
